<template>
  <div class="values-page app-page">
    <div class="page-header">
      <div class="header-left">
        <el-button class="back-btn" text circle @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
        <h2 class="app-section-title">参数值管理</h2>
      </div>
      <div class="actions">
        <el-button type="primary" @click="openCreate">新建参数值</el-button>
      </div>
    </div>

    <el-table :data="records" v-loading="loading" border style="width:100%">
      <el-table-column prop="paramKey" label="参数Key" min-width="220" />
      <el-table-column prop="scopeType" label="范围" width="120" />
      <el-table-column prop="scopeValue" label="范围值" width="160" />
      <el-table-column prop="paramValue" label="参数值" min-width="180" />
      <el-table-column prop="version" label="版本" width="120" />
      <el-table-column prop="effectiveTime" label="生效时间" width="180" />
      <el-table-column prop="expireTime" label="失效时间" width="180" />
      <el-table-column prop="priority" label="优先级" width="100" />
      <el-table-column label="启用" width="100">
        <template #default="scope">
          <el-switch :model-value="scope.row.isActive === 1" @change="(v)=>toggle(scope.row, v)" />
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="visible" title="新建参数值" width="520px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="96px">
        <el-form-item label="参数ID" prop="paramId">
          <el-input v-model.number="form.paramId" :disabled="!!prefillParamId" />
        </el-form-item>
        <el-form-item label="范围类型" prop="scopeType">
          <el-select v-model="form.scopeType" placeholder="请选择范围">
            <el-option v-for="s in scopeTypes" :key="s" :label="s" :value="s" />
          </el-select>
        </el-form-item>
        <el-form-item label="范围值" prop="scopeValue" v-if="form.scopeType !== 'GLOBAL'">
          <el-input v-model.trim="form.scopeValue" placeholder="如关区代码/企业ID/用户ID" />
        </el-form-item>
        <el-form-item label="参数值" prop="paramValue">
          <el-input v-model="form.paramValue" />
        </el-form-item>
        <el-form-item label="版本" prop="version">
          <el-input v-model.trim="form.version" placeholder="如 v1.0" />
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker v-model="timeRange" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="form.priority" :min="0" :max="1000" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="visible=false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getParamValues, createParamValue, toggleParamValue } from '@/assets/api/mobile'
import { ArrowLeft } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const records = ref([])
const visible = ref(false)
const submitting = ref(false)
const formRef = ref()
const form = ref({
  paramId: undefined,
  scopeType: 'GLOBAL',
  scopeValue: '',
  paramValue: '',
  version: 'v1.0',
  effectiveTime: undefined,
  expireTime: undefined,
  priority: 100,
  isActive: 1
})
const timeRange = ref()
const scopeTypes = ['GLOBAL','CUSTOMS_CODE','ENTERPRISE','USER']
const prefillParamId = Number(route.query.paramId)

const rules = {
  paramId: [{ required: true, message: '请输入参数ID', trigger: 'blur' }],
  scopeType: [{ required: true, message: '请选择范围类型', trigger: 'change' }],
  paramValue: [{ required: true, message: '请输入参数值', trigger: 'blur' }]
}

const loadData = async () => {
  loading.value = true
  try {
    const res = await getParamValues({ paramId: prefillParamId || undefined, pageNum: 1, pageSize: 50 })
    const data = res?.data?.data || res?.data || {}
    records.value = Array.isArray(data?.records) ? data.records : (Array.isArray(data?.list) ? data.list : [])
  } finally {
    loading.value = false
  }
}

const openCreate = () => {
  form.value = {
    paramId: prefillParamId || undefined,
    scopeType: 'GLOBAL',
    scopeValue: '',
    paramValue: '',
    version: 'v1.0',
    effectiveTime: undefined,
    expireTime: undefined,
    priority: 100,
    isActive: 1
  }
  timeRange.value = undefined
  visible.value = true
}

const submit = () => {
  formRef.value?.validate(async (ok) => {
    if (!ok) return
    submitting.value = true
    try {
      if (timeRange.value?.length === 2) {
        form.value.effectiveTime = timeRange.value[0]
        form.value.expireTime = timeRange.value[1]
      } else {
        delete form.value.effectiveTime
        delete form.value.expireTime
      }
      const payload = { ...form.value }
      ;['scopeValue','version'].forEach(k=>{ if (payload[k] === '') delete payload[k] })
      const res = await createParamValue(payload)
      const ok = res?.data?.code === 200 || res?.data === true
      if (ok) {
        ElMessage.success('保存成功')
        visible.value = false
        await loadData()
      } else {
        ElMessage.error(res?.data?.message || '保存失败')
      }
    } catch (e) {
      ElMessage.error(e?.response?.data?.message || '保存失败')
    } finally {
      submitting.value = false
    }
  })
}

const toggle = async (row, val) => {
  try {
    await toggleParamValue(row.id, val ? 1 : 0)
    ElMessage.success('已更新状态')
    await loadData()
  } catch (e) {
    ElMessage.error('切换失败')
  }
}

const goBack = () => {
  router.push('/param-engine/definitions')
}

onMounted(loadData)
</script>

<style scoped>
.values-page { position: relative; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.header-left { display: flex; align-items: center; gap: 8px; }
.back-btn { padding: 6px; }
</style>


